"""
@author: yinjx
@file: bookcategory.py
@time: 2023/8/7 19:31
"""

from models.user import Book
from flask import Blueprint, jsonify, request
from flask_restful import Api, Resource
from models.user import Book, Category
from models import db
from models.user import BookCategory
from libs.response import generate_response
import json
from . import category_bp

api = Api(category_bp)


class CategoryBooks(Resource):
    def get(self, category_id):
        category = Category.query.get(category_id)

        if not category:
            return jsonify({'message': 'Category not found'}), 404

        books = db.session.query(Book).join(BookCategory).filter(BookCategory.category_id == category_id).all()

        category_data = {
            'id': category.id,
            'name': category.name
        }

        books_data = []

        for book in books:
            book_data = {
                'id': book.id,
                'title': book.title,
                'author': book.author,
                'cover': book.cover,
                'description': book.description
            }
            books_data.append(book_data)

        return jsonify({'category': category_data, 'books': books_data})


api.add_resource(CategoryBooks, "/category/<int:category_id>/books", endpoint="get_category_books")





